#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1
NODE_BIN=/usr/bin/node
WING_BIN=/usr/bin/dae-wing
WEB_SQUASHFS=/usr/share/daed-next/daed-web.squashfs
GEODATA=/usr/share/v2ray

get_config() {
	config_get_bool enabled $1 enabled "0"
	config_get listen_port $1 listen_port "3000"
	config_get log_enabled $1 log_enabled "0"
	config_get log_maxbackups $1 log_maxbackups "1"
	config_get log_maxsize $1 log_maxsize "1"
}

start_service() {
	config_load "daed-next"
	config_foreach get_config "daed-next"

	[ "$enabled" -eq "1" ] || return 1
	[ "$log_enabled" -eq "1" ] && log_path="/var/log/daed-next/daed-next.log" || log_path="/dev/null"
	mkdir -p /var/log/daed-next
	true > /var/log/daed-next/daed-next.log

	# dae-wing
	procd_open_instance dae-wing
	procd_set_param env DAE_LOCATION_ASSET=$GEODATA
	procd_set_param command $WING_BIN run
	procd_append_param command --config "/etc/daed-next/"
	procd_append_param command --logfile "$log_path"
	procd_append_param command --logfile-maxbackups "$log_maxbackups"
	procd_append_param command --logfile-maxsize "$log_maxsize"
	procd_set_param limits core="unlimited"
	procd_set_param limits nofile="1000000 1000000"
	procd_set_param stdout 0
	procd_set_param stderr 0
	procd_set_param respawn 300 5 10
	procd_close_instance dae-wing
}

service_triggers() {
	procd_add_reload_trigger "daed-next"
}

stop_service() {
	sleep 2
	mount_points=$(mount | grep '/tmp/daed-next' | awk '{print $3}')
	for mp in $mount_points; do
		umount -l "$mp" || { echo "Failed to force unmount $mp"; }
	done
}

reload_service() {
	stop
	sleep 2
	start
}
